package com.example.controller;

import com.example.entity.BootEntity;
import com.example.entity.ImageEntity;
import com.example.exception.ServiceException;
import com.example.service.ImageService;
import com.sun.org.apache.regexp.internal.RE;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.management.relation.RelationNotFoundException;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Controller
public class ImageController {

    @Autowired
    private ImageService imageServicel;

    @RequestMapping("/index")
    public String index() {
        return "/index";
    }

    @RequestMapping(value = "/download/{id}")
    public void download(@PathVariable("id") Integer id) {

    }
    @ResponseBody
    @RequestMapping(value = "/deleteMon/{id}" ,method = RequestMethod.DELETE)
    public String deleteMongoDbById(@PathVariable("id") String id) {
        imageServicel.deleteImageMonById(id);
        return "success";
    }
    @RequestMapping(value = "/downMongo/{id}" ,method = RequestMethod.GET)
    public void downloadByMon(@PathVariable("id") String id,HttpServletResponse response) {
        ImageEntity entity = imageServicel.getImageMonById(id);
        BufferedImage image = null;
        InputStream inputStream = null;
        try {
            //这样的一个流没关闭不要进吗,还有流如果能在rpc中传输的话，为什么不直接用呢
            inputStream = new ByteArrayInputStream(entity.getData());
            image = ImageIO.read(inputStream);
            String content = entity.getContentType().split("/")[1];
            ImageIO.write(image,content, response.getOutputStream());
        } catch (IOException e) {
            System.out.println("ImageIO.read(new ByteArrayInputStream(entity.getData())) error");
            e.printStackTrace();
        }
        try {
            if (null != response.getOutputStream())
                response.getOutputStream().close();
            if (null != inputStream)
                inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @ResponseBody
    @RequestMapping(value = "/uploadMongo", method = RequestMethod.POST)
    public String uploadImageByMongo(MultipartFile myfile) {
        if (null == myfile || myfile.isEmpty())
            throw ServiceException.createException("1119");
        // 文件名称用这个origin的，经常用byte数组代替流是因为流要手动关闭肯能
        String id  ="";
        try {
            //StreamUtils.copyToByteArray(myfile.getInputStream()); 返回byte数组，分布式框架只能传序列化数据，不能传inputstream
             id = imageServicel.insertImageByMongo(myfile.getInputStream(),myfile.getContentType(),myfile.getOriginalFilename());
        } catch (IOException e) {
            System.out.println("myfile.getInputStream()");
            e.printStackTrace();
        }
        return id;
    }

    @ResponseBody
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public String uploadImage(MultipartFile myfile) {
        if (null == myfile || myfile.isEmpty())
            throw ServiceException.createException("1119");
        if (myfile.getSize() > 1 * 1024 * 1024)
            throw ServiceException.createException("1120");
        ImageEntity entity = new ImageEntity();
        entity.setContentType(myfile.getContentType());
        System.out.println(myfile.getSize());
        try {
            if (null != myfile.getBytes())
                entity.setData(myfile.getBytes());
        } catch (IOException e) {
            System.out.println("myfile.getBytes error");
            e.printStackTrace();
        }
        imageServicel.insertImage(entity);
        return "success";
    }

    @RequestMapping("/get100")
    public void get100(HttpServletResponse response) {

        getSimpleImage(response);
//两种方法
//        byte[] bytes = new byte[1024];
//        int i =0;
//        try {
//             //inputStream = new FileInputStream(f);
//            while ((i=inputStream.read(bytes))!=-1)
//            {
//                response.getOutputStream().write(bytes,0,i);
//            }
//            response.getOutputStream().flush();
//        }  catch (IOException e) {
//            e.printStackTrace();
//            System.out.println("ioexception e ");
//        }
//        finally {
//            try {
//                if (null!=inputStream)
//                    inputStream.close();
//                response.getOutputStream().close();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
    }

    @RequestMapping("/get100/sync")
    public void get100ByPool(HttpServletResponse response) {

        //是不是这个线程结束后，response就关闭了，response就为null了？？断点试试
        //controller over   runnable into   task start  "Thread-24" java.lang.NullPointerException
        //BufferedImage image = ImageIO.read(inputStream); 不应该啊，空指针也该是response空啊
        //ImageIO.write(image, "jpg", response.getOutputStream());，应该是主线成response关闭了？？
        //at javax.imageio.ImageIO.write(ImageIO.java:1580)，里面的根据response来生成的stream没有判断是否为null就关闭，
        //应该是response已经为null了,获取这个通过response的就不该用线程，应该是下载任务需要，用File试试
        //file可以的，估计是因为没有response的缘故
        Runnable runnable =()->{
            System.out.println("runnable into");
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                System.out.println("InterruptedException e");
                e.printStackTrace();
            }
            System.out.println("task start");
            //getSimpleImage(response);
            File file = new File("d:/changhua.jpg");
            InputStream inputStream = getClass().getClassLoader().getResourceAsStream("html/100.jpg");
            try {
                BufferedImage image = ImageIO.read(inputStream);
                ImageIO.write(image, "jpg", file);
            } catch (IOException e) {
                System.out.println("IOException e");
                e.printStackTrace();
            }
            System.out.println("task vouer");
        };
        Thread thread = new Thread(runnable);
        thread.start();
        System.out.println("controller over");



    }

    private void getSimpleImage(HttpServletResponse response) {
        ClassLoader loader = getClass().getClassLoader();
        //通过类加载器去获取classpath下的资源
        InputStream inputStream = loader.getResourceAsStream("html/100.jpg");
        if (null == inputStream)
            System.out.println("wenjian lujing budui");
        response.setContentType("image/jpg");
        try {
            BufferedImage image = ImageIO.read(inputStream);
            if (null==response)
                System.out.println("response null");
            ImageIO.write(image, "jpg", response.getOutputStream());
        } catch (IOException e) {
            System.out.println("duqu yichang");
            e.printStackTrace();
        }
        if (null != inputStream) {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            if (null != response.getOutputStream())
                response.getOutputStream().close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
